(function () {
	angular
	.module('ydApp.chat', [])
	.config(function ($stateProvider) {
		$stateProvider.state('chat', {
			url: '/chat?docId?chatId?state?docHead?head',
			controller: "chatCtrl",
			cache: false,
			templateUrl: 'views/chats/chat.html'
		});
		
	})
	.controller("chatCtrl", chatCtrl);

	function chatCtrl ($scope, popup, xhr, localStore, $stateParams, reverseFilter, $timeout, $anchorScroll, Cameranav, $ionicLoading, fileTransfer, $q, chatInterval, $ionicHistory) {
		var vm = $scope.vm = {};
		vm.docHead = $stateParams.docHead;
		vm.head = $stateParams.head;
		vm.chatId = '';
		vm.user = localStore.get("user");
		vm.userType = localStore.get("userType");
		vm.queryStartTime = "";
		vm.queryEndTime = "";
		vm.msgs = [];
		vm.confirm = function () {
			if (vm.message.length > 0) {
				return popup.confirm('当前有消息尚未发送，是否取消发送?');
			} else {
				return null;
			}
		}
		vm.over = function () {
			popup.confirm('您正在结束本次咨询，结束后，患者将不能继续发送消息，是否立即结束?').then(function (res) {
				if (res) {
					xhr.get('HealthInquiry/com/call/overCall', {
						id: vm.chatId,
						toUser: vm.user.id
					}).then(function (res) {
						vm.call.state = 2;
						popup.alert('咨询成功结束').then(function () {
							$ionicHistory.goBack();
						});
					})
				}
			});
		}
		vm.loadMsg = function() {
			return xhr.get('HealthInquiry/com/callMsg/callMsgs', {
				callId: vm.chatId,
				userId: vm.user.id,
				queryEndTime: vm.queryStartTime,
				sortField: 'sendTime',
				sortOrder: 'desc',
				pageSize: 10,
			}).then(function (res) {
				console.log(res)
				if (res.successful) {
					if (res.data.length > 0) {
						vm.queryStartTime = res.data[0].queryStartTimeString;
						vm.queryEndTime = res.data[0].queryEndTimeString;
						var msgs = reverseFilter(res.data);
						vm.msgs = msgs.concat(vm.msgs);
					}
				}
			}).finally(function () {
				$scope.$broadcast('scroll.refreshComplete');
			})
		};
		function startInteval() {
			chatInterval.interval = setInterval(function () {
				if (!vm.call || vm.call.state == 2) {
					return;
				}
				xhr.get('HealthInquiry/com/callMsg/callMsgs', {
					callId: vm.chatId,
					userId: vm.user.id,
					queryStartTime: vm.queryEndTime,
					sortField: 'sendTime',
					sortOrder: 'desc',
					pageSize: 10,
				}, true).then(function (res) {
					if (res.successful) {
						for (var i = 0; i < res.data.length; i++) {
							var check = true;
							for (var j = 0; j < vm.msgs.length; j++) {
								if (vm.msgs[j].id == res.data[i].id) {
									check = false;
									break;
								}
							}
							if(check){
								vm.msgs.push(res.data[i]);
								messageToBottom();
							}
						}
					}
				}, function (error) {
					clearInterval(chatInterval.interval);
					popup.confirm('加载失败'+error+'?', '重新加载', '返回').then(function (ok) {
						if (ok) {
							startInteval();
						} else {
							$ionicHistory.goBack();
						}
					});
				})
			}, 1000)
		}
		startInteval();
		
		var ispost = false;
		vm.sendMsg = function (userId, message, msgType) {
			if (!vm.message || ispost) {
				return;
			}
			ispost = true;
			xhr.get('HealthInquiry/com/callMsg/sendMsg', {
				callId: vm.chatId,
				userId: userId || vm.user.id,
				content: message || vm.message,
				msgType: msgType || 0
			}).then(function (res) {
				vm.msgs.push(res.data);
				vm.message = "";
				messageToBottom();
			}).finally(function () {
				ispost = false;
			});
		};
		vm.getImage = function () {
			Cameranav.getPicture(function(imgUri) {
                $ionicLoading.show({
                    template: '正在上传…'
                });
                fileTransfer.upload(imgUri, vm.user.id, function(res) {
                	$ionicLoading.hide();
                    if (res.successful) {
                    	vm.message = "  ";
                    	vm.sendMsg(vm.user.id, res.data.picUrl, 1);
					}
                });
            })
		}
		vm.keyup = function ($event) {
			if ($event.keyCode == 13) {
				vm.sendMsg(vm.user.id, vm.message);
			}
		};
		function messageToBottom() {
            $timeout(function () {
                $anchorScroll("msg-bottom", 0);
            }, 0);
        };
		(function (startCall) {
			startCall().then(function () {
				vm.loadMsg().then(function (res) {
					messageToBottom();
				});
			});
		})(function () {
			var defer = $q.defer();
			if ($stateParams.docId) {
				xhr.get('HealthInquiry/com/call/startCall', {
					fromUser: vm.user.id,
					toUser: $stateParams.docId
				}).then(function (res) {
					if (res.successful) {
						vm.call = res.data;
						vm.chatId = res.data.id;
						vm.topTitle = res.resultMsg;
					}
					defer.resolve(res);
				}, function (err) {
					defer.reject();
					$ionicHistory.goBack();
				});
			} else {
				vm.chatId = $stateParams.chatId;
				vm.call = {
					chatId: $stateParams.chatId,
					state: $stateParams.state
				};
				defer.resolve();
			}
			return defer.promise;
			
		});
	}
})();